<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>文章详情</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: linear-gradient(to right, #2c3e50, #3498db);
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        h2, h3 {
            color: #333;
        }

        #article-container, #comment-container {
            background-color: #fff;
            padding: 20px;
            margin: 20px 0;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            width: 90%;
            max-width: 800px;
        }

        #author, #created_at {
            color: #555;
            font-size: 14px;
        }

        #content {
            margin-top: 20px;
            line-height: 1.6;
        }

        #comments div {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        #commentForm textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            margin-bottom: 10px;
            font-size: 14px;
        }

        #commentForm button {
            background-color: #008cba;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }

        #commentForm button:hover {
            background-color: #005f7f;
        }

        a {
            color: #008cba;
            text-decoration: none;
        }

        a:hover {
            text-decoration: underline;
        }

        .comment-author {
            font-weight: bold;
            color: #333;
        }

        .comment-date {
            color: #888;
            font-size: 12px;
        }

        .like-article-btn, .like-comment-btn {
            background-color: gray;
            color: white;
            border: none;
            cursor: pointer;
            padding: 10px 10px;
            border-radius: 5px;
            font-size: 16px;
        }

        .like-article-btn.liked, .like-comment-btn.liked {
            background-color: red;
        }

        .icon-like {
            margin-right: 5px;
        }
    </style>
</head>
<body>
    <div id="article-container">
        <h2 id="title"></h2>
        <p id="author"></p>
        <p id="created_at"></p>
        <p id="content"></p>
        <button id="favoriteButton" style="display:none;" onclick="addFavorite()">收藏</button>
        <button class="like-article-btn" data-article-id="1">
            <i class="icon-like">👍</i> <span class="like-count">0</span>
        </button>
        <p><a href="profile.html">返回个人资料</a></p>
    </div>

    <div id="comment-container">
        <h3>评论</h3>
        <div id="comments"></div>

        <h3>添加评论</h3>
        <form id="commentForm">
            <input type="hidden" name="article_id" id="article_id">
            <textarea name="comment" id="comment" required placeholder="输入您的评论"></textarea><br>
            <button type="submit">提交评论</button>
        </form>
    </div>

    <script>
        const urlParams = new URLSearchParams(window.location.search);
        const articleId = urlParams.get('id');

        function parseJwt(token) {
            try {
                const base64Url = token.split('.')[1];
                const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
                const jsonPayload = decodeURIComponent(atob(base64).split('').map(c => `%${('00' + c.charCodeAt(0).toString(16)).slice(-2)}`).join(''));
                return JSON.parse(jsonPayload);
            } catch (e) {
                return null;
            }
        }

        function getCookie(name) {
            const value = `; ${document.cookie}`;
            const parts = value.split(`; ${name}=`);
            if (parts.length === 2) return parts.pop().split(';').shift();
        }

        const jwt = getCookie('token');
        const currentUser = jwt ? parseJwt(jwt) : null;
        const currentUserId = currentUser ? currentUser.data.id : null;

        const favoriteButton = document.getElementById('favoriteButton');
        if (currentUserId) {
            favoriteButton.style.display = 'block';
        }

        document.addEventListener('DOMContentLoaded', function() {
            if (articleId) {
                document.getElementById('article_id').value = articleId;

                fetch(`get_article_detail.php?id=${articleId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.error) {
                            document.getElementById('title').textContent = '未找到文章';
                        } else {
                            document.getElementById('title').textContent = data.title;
                            document.getElementById('author').textContent = `作者: ${data.author}`;
                            document.getElementById('created_at').textContent = `发布时间: ${data.created_at}`;
                            document.getElementById('content').innerHTML = data.content.replace(/\n/g, '<br>');

                            const commentsDiv = document.getElementById('comments');
                            commentsDiv.innerHTML = '';
                            if (data.comments.length > 0) {
                                data.comments.forEach(comment => {
                                    const commentElement = document.createElement('div');
                                    commentElement.innerHTML = `
                                        <p>${comment.comment}</p>
                                        <p class="comment-author">评论者: ${comment.commenter} <span class="comment-date">${comment.created_at}</span></p>
                                        ${currentUserId === comment.commenter_id ? `<button onclick="deleteComment(${comment.comment_id})">删除</button>` : ''}
                                        <button class="like-comment-btn" data-comment-id="${comment.comment_id}">
                                            <i class="icon-like">👍</i> <span class="like-count">0</span>
                                        </button>
                                    `;
                                    commentsDiv.appendChild(commentElement);
                                });

                                document.querySelectorAll('.like-comment-btn').forEach(button => {
                                    const commentId = button.dataset.commentId;
                                    fetch(`get_comment_like_status.php?comment_id=${commentId}`)
                                        .then(response => response.json())
                                        .then(data => {
                                            if (data.liked) {
                                                button.classList.add('liked');
                                            }
                                            button.querySelector('.like-count').textContent = data.like_count;
                                        });

                                    button.addEventListener('click', function() {
                                        fetch('like_comment.php', {
                                            method: 'POST',
                                            headers: {
                                                'Content-Type': 'application/x-www-form-urlencoded',
                                            },
                                            body: 'comment_id=' + commentId
                                        })
                                        .then(response => response.json())
                                        .then(data => {
                                            const likeCountElement = button.querySelector('.like-count');
                                            let likeCount = parseInt(likeCountElement.textContent);
                                            if (data.status === 'liked') {
                                                button.classList.add('liked');
                                                likeCountElement.textContent = likeCount + 1;
                                                alert('点赞成功！');
                                            } else if (data.status === 'unliked') {
                                                button.classList.remove('liked');
                                                likeCountElement.textContent = likeCount - 1;
                                                alert('取消点赞成功！');
                                            } else {
                                                alert('操作失败: ' + data.message);//提示错误信息
                                            }
                                        });
                                    });
                                });

                                document.querySelectorAll('.like-article-btn').forEach(button => {
                                    fetch(`get_article_like_status.php?article_id=${articleId}`)
                                        .then(response => response.json())
                                        .then(data => {
                                            if (data.liked) {
                                                button.classList.add('liked');
                                            }
                                            button.querySelector('.like-count').textContent = data.like_count;
                                        });

                                    button.addEventListener('click', function() {
                                        fetch('like_article.php', {
                                            method: 'POST',
                                            headers: {
                                                'Content-Type': 'application/x-www-form-urlencoded',
                                                'Authorization': jwt
                                            },
                                            body: 'article_id=' + articleId
                                        })
                                        .then(response => response.json())
                                        .then(data => {
                                            const likeCountElement = button.querySelector('.like-count');
                                            let likeCount = parseInt(likeCountElement.textContent);
                                            if (data.status === 'liked') {
                                                button.classList.add('liked');
                                                likeCountElement.textContent = likeCount + 1;
                                                alert('点赞成功！');
                                            } else if (data.status === 'unliked') {
                                                button.classList.remove('liked');
                                                likeCountElement.textContent = likeCount - 1;
                                                alert('取消点赞成功！');
                                            } else {
                                                alert('操作失败: ' + data.message);
                                            }
                                        });
                                    });
                                });
                            } else {
                                commentsDiv.textContent = '暂无评论';
                            }

                            document.querySelectorAll('.like-article-btn').forEach(button => {
                                    fetch(`get_article_like_status.php?article_id=${articleId}`)
                                        .then(response => response.json())
                                        .then(data => {
                                            if (data.liked) {
                                                button.classList.add('liked');
                                            }
                                            button.querySelector('.like-count').textContent = data.like_count;
                                        });

                                    button.addEventListener('click', function() {
                                        fetch('like_article.php', {
                                            method: 'POST',
                                            headers: {
                                                'Content-Type': 'application/x-www-form-urlencoded',
                                                'Authorization': jwt
                                            },
                                            body: 'article_id=' + articleId
                                        })
                                        .then(response => response.json())
                                        .then(data => {
                                            const likeCountElement = button.querySelector('.like-count');
                                            let likeCount = parseInt(likeCountElement.textContent);
                                            if (data.status === 'liked') {
                                                button.classList.add('liked');
                                                likeCountElement.textContent = likeCount + 1;
                                                alert('点赞成功！');
                                            } else if (data.status === 'unliked') {
                                                button.classList.remove('liked');
                                                likeCountElement.textContent = likeCount - 1;
                                                alert('取消点赞成功！');
                                            } else {
                                                alert('操作失败: ' + data.message);
                                            }
                                        });
                                    });
                                });

                        }
                    })
                    .catch(error => console.error('获取文章详情失败：', error));
            } else {
                document.getElementById('title').textContent = '未提供文章ID';
            }
        });

        document.getElementById('commentForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            if (!jwt) {
                alert('请先登录');
                return;
            }
            fetch('submit_comment.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('评论提交成功');
                    location.reload();
                } else {
                    alert('评论提交失败: ' + data.error);
                }
            })
            .catch(error => console.error('提交评论失败：', error));
        });

        function deleteComment(commentId) {
            const jwt = getCookie('token');
            if (!jwt) {
                alert('请先登录');
                return;
            }
            const formData = new FormData();
            formData.append('comment_id', commentId);
            fetch('delete_comment.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('评论删除成功');
                    location.reload();
                } else {
                    alert('评论删除失败: ' + data.error);
                }
            })
            .catch(error => console.error('删除评论失败：', error));
        }

        function addFavorite() {
            const jwt = getCookie('token');
            if (!jwt) {
                alert('请先登录');
                return;
            }
            const formData = new FormData();
            formData.append('article_id', articleId);
            fetch('addFavorite.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.message) {
                    alert(data.message);
                } else {
                    alert('收藏失败: ' + data.error);
                }
            })
            .catch(error => console.error('添加收藏失败：', error));
        }
    </script>
</body>
</html>


